package sw6.pc.network;

import java.io.*;
import java.net.*;

public class Client {

	Socket mClientSocket = null;
	DataOutputStream mOutput = null;
	DataInputStream mInput = null;

	public boolean connect(String ip, int port) throws UnknownHostException, IOException {
		// Connects the socket to a server, and gets the input and output stream of the socket
		mClientSocket = new Socket(ip, port);
		mOutput = new DataOutputStream(mClientSocket.getOutputStream());
		mInput = new DataInputStream(mClientSocket.getInputStream());

		return true;
	}

	public DataOutputStream getOutputStream() {
		return mOutput;
	}

	public DataInputStream getInputStream() {
		return mInput;
	}

	public void writeObject(Object obj) throws IOException {
		// Serializes the object obj to a byte array, and sends the array though the socket.
		// The length of the socket is sent, so that the reciever will know how many bytes it should read.
		byte[] bytes = Serializer.serializeObject(obj);
		mOutput.writeInt(bytes.length);
		mOutput.write(bytes);
	}

	public <T> T readObject(Class<T> someClass) throws IOException {
		// Reads the length of the byte array
		int length = mInput.readInt();
		byte[] data = new byte[length];

		// Reads the bytes from the input stream
		for (int i = 0; i < length; i++)
		{
			data[i] = mInput.readByte();
		}

		// Deserializes the recieved object, using the byte array
		return Serializer.deSerializeObject(data, someClass);
	}

	public void close() throws IOException {
		// Closes the connection
		mClientSocket.close();
		mOutput.close();
		mInput.close();
	}
}